package com.zh.risk.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.entity.Oauth;
import com.zh.risk.dao.IpTableDao;
import com.zh.risk.entity.IpTable;
import com.zh.risk.entity.RiskBlackList;
import com.zh.risk.service.IpTableService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.BindingType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 黑名单白名单业务实现
 * @Author: Liard
 * @Create in: 2020/8/24 11:38
 * @Version: 1.0.1
 */
@Service
public class IpTableServiceImpl extends ServiceImpl<IpTableDao, IpTable> implements IpTableService {

    @Autowired
    private IpTableDao dao;

    @Override
    public IPage<IpTable> getBlackList(Page<IpTable> page, IpTable param) {
        return dao.selectPage(page, new LambdaQueryWrapper<IpTable>()
                .eq(Objects.nonNull(param.getStatus()), IpTable::getStatus, param.getStatus())
                .like(StrUtil.isNotEmpty(param.getIp()), IpTable::getIp, param.getIp())
                .eq(Objects.nonNull(param.getType()), IpTable::getType, param.getType())
                .between(ObjectUtils.allNotNull(param.getAddStartTime(), param.getAddEndTime()),
                        IpTable::getCreateDate, param.getAddStartTime(), param.getAddEndTime())
        );
    }

    @Override
    public boolean addBlackList(IpTable param) {
        String ip = param.getIp();
        String[] ipArr;
        List<IpTable> list = new ArrayList<>();
        // 获取当前操作人对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Oauth auth = (Oauth) authentication.getPrincipal();
        if (ip.indexOf(",") > 0) {
            ipArr = ip.split(",");
            for (int i = 0; i < ipArr.length; i++) {
                IpTable ipTable = new IpTable();
                ipTable.setCreateDate(DateUtil.now());
                ipTable.setOp(auth.getUserLoginName());
                ipTable.setStatus(param.getStatus());
                ipTable.setType(param.getType());
                ipTable.setIp(ipArr[i]);
                ipTable.setSys(1);
                list.add(ipTable);
            }
            return saveBatch(list);
        } else if (ip.indexOf("，") > 0) {
            ipArr = ip.split("，");
            for (int i = 0; i < ipArr.length; i++) {
                IpTable ipTable = new IpTable();
                ipTable.setCreateDate(DateUtil.now());
                ipTable.setOp(auth.getUserLoginName());
                ipTable.setStatus(param.getStatus());
                ipTable.setType(param.getType());
                ipTable.setIp(ipArr[i]);
                ipTable.setSys(1);
                list.add(ipTable);
            }
            return saveBatch(list);
        }
        param.setSys(1);
        param.setCreateDate(DateUtil.now());
        param.setOp(auth.getUserLoginName());
        return save(param);
    }

    @Override
    public int modBlackList(IpTable param) {
        return dao.update(param, new LambdaQueryWrapper<IpTable>().eq(IpTable::getId, param.getId()));
    }

    @Override
    public int delBlackInfo(IpTable param) {
        return dao.delete(new LambdaQueryWrapper<IpTable>().eq(IpTable::getId, param.getId()));
    }


    @Override
    public int delBatBlackInfo(List<Integer> param) {
        return dao.deleteBatchIds(param);
    }

    @Override
    public boolean addIpTableByExcel(MultipartFile file) {
        boolean reslut =false;
        if(file.isEmpty()) return false;
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."), file.getOriginalFilename().length());
        if(!Objects.equals(fileType,".xlsx") || !Objects.equals(fileType,".xls"))return false;
        try{
            // 获取当前操作人对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Oauth auth = (Oauth) authentication.getPrincipal();
            List<IpTable> ipTablesLists = new ArrayList<IpTable>();
            Workbook workbook = null;
            workbook = WorkbookFactory.create(file.getInputStream());
            file.getInputStream().close();
            //获取所有的工作表的的数量
            int numOfSheet = workbook.getNumberOfSheets();
            //遍历这个这些表
            for (int i = 0; i < numOfSheet; i++) {
                //获取一个sheet也就是一个工作簿
                Sheet sheet = workbook.getSheetAt(i);
                int lastRowNum = sheet.getLastRowNum();
                //从第一行开始第一行一般是标题
                for (int j = 1; j <= lastRowNum; j++) {
                    Row row = sheet.getRow(j);
                    //获取单元格的值
                    String ip = row.getCell(0).getStringCellValue();
                    String status = row.getCell(1).getStringCellValue();
                    String type = row.getCell(2).getStringCellValue();
                    IpTable ipTable = new IpTable();
                    ipTable.setCreateDate(DateUtil.now());
                    ipTable.setOp(auth.getUserLoginName());
                    ipTable.setStatus(Integer.valueOf(status));
                    ipTable.setType(Integer.valueOf(type));
                    ipTable.setIp(ip);
                    ipTable.setSys(1);
                    ipTablesLists.add(ipTable);
                }
            }
            //批量新增
            if (ipTablesLists.size()>0) {
                reslut = this.saveBatch(ipTablesLists, ipTablesLists.size());
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return  reslut;
    }
}
